<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索与添加 -->
      <el-row :gutter="15">
        <el-col :span="8">
          <el-input placeholder="请输入内容" @clear="getUserList" clearable v-model="queryInfo.query"
            @keyup.enter.native="getUserList" class="input-with-select">
            <el-button slot="append" @click="getUserList" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisibleAdd = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column prop="index" label="序号" width="80" align="center">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="width">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="width">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="width">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="width">
        </el-table-column>
        <el-table-column label="状态" width="width">
          <template slot-scope="{row}">
            <el-switch @change="userStateChanged(row)" v-model="row.mg_state">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="{row}">
            <el-button type="primary" @click="showEditDialog(row)" title="修改" size="mini" icon="el-icon-edit">
            </el-button>

            <el-popconfirm title="这是一段内容确定删除吗？" @confirm="delUserById(row.id)">

              <el-button type="danger" style="margin:0 12px" title="删除" slot="reference" size="mini"
                icon="el-icon-delete">
              </el-button>
            </el-popconfirm>

            <el-button type="warning" @click="setRole(row)" title="分配角色" size="mini" icon="el-icon-setting"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加用户的对话框 -->
      <el-dialog title="添加用户信息" @close="addDialogClosed" :visible.sync="dialogVisibleAdd" width="50%">
        <el-form ref="formAdd" :rules="addRules" :model="addFrom" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addFrom.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addFrom.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addFrom.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addFrom.mobile"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleAdd = false">取 消</el-button>
          <el-button type="primary" @click="submitFromAdd">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户的对话框 -->
      <el-dialog title="修改用户信息" @close="editDialogClosed" :visible.sync="dialogVisibleEdit" width="50%">
        <el-form ref="formEdit" :rules="addRules" :model="editFrom" label-width="70px">
          <el-form-item label="用户名">
            <el-input v-model="editFrom.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editFrom.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editFrom.mobile"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleEdit = false">取 消</el-button>
          <el-button type="primary" @click="submitFromEdit">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色的对话框 -->
      <el-dialog title="分配角色信息" @close="setDialogClosed" :visible.sync="dialogVisibleSet" width="50%">
        <div>
          <p>当前用户 : {{userInfo.username}}</p>
          <p>当前角色 : {{userInfo.role_name}}</p>
          <p>分配新角色 :
            <el-select v-model="selectRoleId" placeholder="请选择">
              <el-option v-for="item in rolesList" :key="item.value" :label="item.roleName" :value="item.id">
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleSet = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
        </span>
      </el-dialog>


      <!-- 分页器 -->
      <el-pagination style="text-align:center;margin-top:20px" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[3, 5, 10]"
        :page-size="queryInfo.pagesize" layout="prev, pager, next, jumper,->,total, sizes" :total="total">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
  export default {
    name: "User",
    data() {
      //验证邮箱
      let checkEmail = (rule, value, cb) => {
        const regEmail = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
        if (regEmail.test(value)) {
          return cb()
        }
        cb(new Error("请输入合法的邮箱"))
      }
      //验证手机号
      let checkMobile = (rule, value, cb) => {
        const regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        if (regMobile.test(value)) {
          return cb()
        }
        cb(new Error("请输入合法的手机号"))
      }
      return {
        //发送请求需要的值
        queryInfo: {
          query: "", //输入框的值
          pagenum: 1, //当前第几页
          pagesize: 5, //当前一页展示多少数据
        },
        userList: [], //用户数据
        total: 0, //总数据条数
        dialogVisibleAdd: false, //添加用户对话框的隐藏与显示
        dialogVisibleEdit: false, //修改用户对话框的隐藏与显示
        dialogVisibleSet: false, //分配用户对话框的隐藏与显示
        userInfo: {}, //分配角色的当前单个信息
        rolesList: [], //角色的数据列表
        selectRoleId: "", //已选中的角色id值
        //用来保存请求的修改单个数据
        editFrom: {},

        //添加用户表单数据
        addFrom: {
          username: "",
          password: "",
          email: "",
          mobile: ""

        },
        //添加用户的表单验证
        addRules: {
          username: [{
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 10,
              message: '用户名的长度在3~10个字符',
              trigger: 'blur'
            }
          ],
          password: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 15,
              message: '用户名的长度在6~15个字符',
              trigger: 'blur'
            }
          ],
          email: [{
              required: true,
              message: '请输入邮箱',
              trigger: 'blur'
            },
            {
              validator: checkEmail,
              trigger: "blur"
            }
          ],
          mobile: [{
              required: true,
              message: '请输入手机号',
              trigger: 'blur'
            },
            {
              validator: checkMobile,
              trigger: "blur"
            }
          ],
        },
      }
    },
    methods: {
      //获取用户列表
      async getUserList() {
        let result = await this.$requests.get("users", {
          params: this.queryInfo
        })
        if (result.meta.status == 200) {
          this.userList = result.data.users
          this.total = result.data.total
        } else {
          console.log("error")
        }
      },
      //pagesize改变触发
      handleSizeChange(page) {
        this.queryInfo.pagesize = page
        this.getUserList()
      },
      //监听页码值的变化
      handleCurrentChange(count) {
        this.queryInfo.pagenum = count
        this.getUserList()
      },
      //监听状态开关的改变
      async userStateChanged(value) {
        let result = await this.$requests.put(`users/${value.id}/state/${value.mg_state}`)
        if (result.meta.status == 200) {
          this.$message({
            message: '修改状态成功',
            type: 'success'
          });
        } else {
          value.mg_state = !value.mg_state
          this.$message('修改失败');
        }
      },
      //添加用户的表单提交
      submitFromAdd() {
        this.$refs.formAdd.validate(async (valid) => {
          if (valid) {
            this.dialogVisibleAdd = false
            let result = await this.$requests.post("users", this.addFrom)
            if (result.meta.status == 201) {
              this.$message({
                message: '添加信息成功',
                type: 'success'
              });
              this.getUserList()
            } else {
              this.$message('添加信息失败');
            }
          } else {
            this.$message('添加信息失败');
            return false;
          }
        });
      },
      //监听添加用户对话框关闭的事件
      addDialogClosed() {
        this.$refs.formAdd.resetFields()
      },
      //监听修改用户对话框关闭的事件
      editDialogClosed() {
        this.$refs.formEdit.resetFields()
      },
      //修改用户的按钮回调
      async showEditDialog(row) {
        this.dialogVisibleEdit = true
        let result = await this.$requests.get(`users/${row.id}`)
        if (result.meta.status == 200) {
          this.editFrom = result.data
        } else {
          console.log("error")
        }
      },
      //修改用户的表单提交
      submitFromEdit() {
        this.$refs.formEdit.validate(async (valid) => {
          if (valid) {
            this.dialogVisibleEdit = false
            //发起请求
            let result = await this.$requests.put(`users/${this.editFrom.id}`, {
              email: this.editFrom.email,
              mobile: this.editFrom.mobile
            })
            if (result.meta.status == 200) {
              this.$message({
                message: '修改信息成功',
                type: 'success'
              });
              this.getUserList()
            } else {
              this.$message('修改信息失败');
            }
          } else {
            this.$message('修改信息失败');
            return false;
          }
        });
      },
      //删除某一条用户数据
      async delUserById(id) {
        let result = await this.$requests.delete(`users/${id}`)
        if (result.meta.status == 200) {
          this.$message({
            message: '删除信息成功',
            type: 'success'
          });
          this.getUserList()
        } else {
          this.$message(`${result.meta.msg}`);
        }
      },
      //分配角色按钮的回调
      async setRole(row) {
        //获取所有角色列表
        let result = await this.$requests.get("roles")
        if (result.meta.status == 200) {
          this.rolesList = result.data
        } else {
          this.$message("获取信息失败")
        }
        this.dialogVisibleSet = true
        this.userInfo = row
      },
      //点击按钮分配角色 
      async saveRoleInfo() {
        if (!this.selectRoleId) {
          return this.$message.error("请选择要分配的角色")
        }
        let result = await this.$requests.put(`users/${this.userInfo.id}/role`, {
          rid: this.selectRoleId
        })
        if (result.meta.status == 200) {
          this.$message.success("更新角色成功")
          this.getUserList()
        } else {
          return this.$message.error("更新角色失败")
        }
        this.dialogVisibleSet = false
      },
      //清空分配角色对话框的信息
      setDialogClosed() {
        this.selectRoleId = ""
        this.userInfo = {}
      }
    },
    mounted() {
      this.getUserList()
    }


  }

</script>

<style lang="less" scoped>


</style>
